package com.novellotus.iov.carvice.activity;


import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.DataSign;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.rengwuxian.materialedittext.validation.RegexpValidator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;

/**
 * 关注车辆
 */
public class AttentionActivity extends BaseActivity {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.edt_plate)
    MaterialEditText edt_plate;
    @BindView(R.id.edt_vin)
    MaterialEditText edt_vin;
    @BindView(R.id.btn_sure)
    Button btn_sure;
    boolean update = false;
    Observable<CharSequence> observablePlate;
    Observable<CharSequence> observableVin;

    String checkPlate = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1,2}$";

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_attention);
    }

    @Override
    public void init() {
        edt_plate.addValidator(new RegexpValidator(getResources().getString(R.string.plate_wrong), checkPlate));
        tv_tittle.setText(getResources().getString(R.string.monitoring_vehicle));
        setEdt_plate();
        setEdt_vin();
        setFollowVehicle();
        confirm();
    }

    /**
     * 设置车牌编辑框
     */
    private void setEdt_plate() {

        observablePlate = RxTextView.textChanges(edt_plate);
        observablePlate.compose(RxSchedulers.<CharSequence>lifecycle(this))
                .compose(RxSchedulers.<CharSequence>compose())
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence pass) {
                        super.onNext(pass);
                        if (pass.length() >= 7) {
                            edt_plate.validate();
                        }
                    }
                });
    }

    /**
     * 设置车架号编辑框
     */
    private void setEdt_vin() {
        observableVin = RxTextView.textChanges(edt_vin);
//        observableVin.subscribe(new MyObserver<CharSequence>() {
//            @Override
//            public void onNext(CharSequence value) {
//                super.onNext(value);
//                if (value.length() == 17) {
//                    edt_vin.setTextColor(getResources().getColor(R.color.text_black));
//                } else {
//                    edt_vin.setTextColor(getResources().getColor(R.color.textTipsRed));
//
//                }
//            }
//        });


        observableVin.compose(RxSchedulers.<CharSequence>lifecycle(this))
                .compose(RxSchedulers.<CharSequence>compose())
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence pass) {
                        super.onNext(pass);
                        if (pass.length() == 17) {

                            if (MyUtils.isVin(pass.toString())) {
                                edt_vin.setError(null);
                            } else {
                                edt_vin.setError(getResources().getString(R.string.vin_wrong));
                            }

                        }
                    }
                });
    }

    private void confirm() {
        Observable.combineLatest(observablePlate, observableVin, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence plate, CharSequence vin) throws Exception {
                return MyUtils.isPlate(plate.toString()) || (vin.length() == 17 && MyUtils.isVin(vin.toString()));
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    MyViewUtils.setButtonClickable(btn_sure, true);
                } else {
                    MyViewUtils.setButtonClickable(btn_sure, false);
                }
            }
        });
    }

    /**
     * 点击登陆按钮
     */
    public void setFollowVehicle() {
        RxView.clicks(btn_sure).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                JSONObject requestData = new JSONObject();
                try {
                    requestData.put("pn", edt_plate.getText().toString());
                    requestData.put("vin", edt_vin.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().followVehicle(DataSign.getSign(requestData.toString(), AttentionActivity.this));
                observable.compose(RxSchedulers.<BaseEntity<Object>>compose())
                        .subscribe(new BaseObserver<Object>(AttentionActivity.this) {
                            @Override
                            public void onSuccess(Object response) {
                                MyUtils.showToast(AttentionActivity.this, "关注车辆成功!");
                                update = true;
                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(AttentionActivity.this, msg);
                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(AttentionActivity.this, msg);
                            }
                        });
            }
        });
    }


    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//            if (update) {
//                Intent intent = new Intent(this, MainActivityOld.class);
//                intent.putExtra("isUpdate", true);
//                setResult(101, intent);
//                finish();
//            } else {
//                finish();
//            }
//            return true;
//        } else {
//            return super.onKeyDown(keyCode, event);
//        }
//
//    }
}
